class Solution {
public:
    Node* copyRandomList(Node* head)
    {
        Node* copytail = nullptr, * copyhead = nullptr;
        Node* cur = head;
        map<Node*, Node*> node;
        while (cur)
        {
            if (copytail == NULL)
            {
                copyhead = copytail = new Node(cur->val);
            }
            else
            {
                copytail->next = new Node(cur->val);
                copytail = copytail->next;
            }
            node[cur] = copytail;
            cur = cur->next;
        }
        Node* copy = copyhead;
        cur = head;
        while (cur)
        {
            if (cur->random == NULL)
            {
                copy->random = NULL;
            }
            else
            {
                copy->random = node[cur->random];
            }
            cur = cur->next;
            copy = copy->next;
        }
        return copyhead;
    }
};